package com.fc.test.api;

import com.fc.test.model.auto.TAbbOrder;
import com.fc.test.model.auto.TAbbTaocan;
import com.fc.test.service.TAbbOrderService;
import com.fc.test.service.TAbbTaocanService;
import com.fc.test.util.HttpUtil;
import com.fc.test.util.JsonUtil;
import com.fc.test.util.wx.Utils.XMLUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/apiOrderController")
@Api(value = "订单")
public class ApiOrderController {
    private static Logger logger= LoggerFactory.getLogger(ApiOrderController.class);

    @Autowired
    private TAbbOrderService orderService;

    @Autowired
    private TAbbTaocanService taocanService;

    @ResponseBody
    @PostMapping(value = "/createCuxiaoOrder",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "创建同城促销订单")
    public String createCuxiaoOrder(
            @ApiParam(value = "用户id") @RequestParam(value = "userid") String userid,
            @ApiParam(value = "商品id") @RequestParam(value = "goodsid") String goodsid,
            @ApiParam(value = "数量") @RequestParam(value = "count") int count,
            @ApiParam(value = "邮寄方式：1包邮；2自提；") @RequestParam(value = "type") int type,
            @ApiParam(value = "收货人姓名") @RequestParam(value = "receiverName") String  receiverName,
            @ApiParam(value = "联系电话") @RequestParam(value = "receiverPhone") String receiverPhone,
            @ApiParam(value = "收货地址") @RequestParam(value = "address") String address
    ){
        Map<String,Object> resMap = orderService.createCuxiaoOrder(userid,goodsid,count,type,receiverName,receiverPhone,address);
        return JsonUtil.jsonMapStr(resMap);
    }

    @ResponseBody
    @PostMapping(value = "/createHuigouOrder",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "创建大商惠购订单")
    public String createHuigouOrder(
            @ApiParam(value = "用户id") @RequestParam(value = "userid") String userid,
            @ApiParam(value = "商品id") @RequestParam(value = "goodsid") String goodsid,
            @ApiParam(value = "数量") @RequestParam(value = "count") int count
    ){
        Map<String,Object> resMap = orderService.createHuigouOrder(userid,goodsid,count);
        return JsonUtil.jsonMapStr(resMap);
    }

    @ResponseBody
    @PostMapping(value = "/getMyCuxiaoOrder",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "我的同城促销订单")
    public String getMyCuxiaoOrder(
            @ApiParam(value = "用户id") @RequestParam(value = "userid") String userid,
            @ApiParam(value = "订单状态1代发货；2待收货；3已完成") @RequestParam(value = "paystatus") int paystatus,
            @ApiParam(value = "页码") @RequestParam(value = "page") int page
    ){
        Map<String,Object> resMap = orderService.getMyCuxiaoOrder(userid,paystatus,page);
        return JsonUtil.jsonMapStr(resMap);
    }

    @ResponseBody
    @PostMapping(value = "/getOrderDetail",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "订单详情")
    public String getOrderDetail(
            @ApiParam(value = "订单id") @RequestParam(value = "orderid") String orderid
    ){
        Map<String,Object> resMap = new HashMap<>();
        resMap = orderService.getOrderDetail(orderid);
        return JsonUtil.jsonMapStr(resMap);
    }


    @ResponseBody
    @PostMapping(value = "/confirmReceipt",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "确认收货")
    public String confirmReceipt(
            @ApiParam(value = "订单id") @RequestParam(value = "orderid") String orderid
    ){
        Map<String,Object> resMap = orderService.confirmReceipt(orderid);
        return JsonUtil.jsonMapStr(resMap);
    }

    @ResponseBody
    @PostMapping(value = "/getMyHuigouOrder",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "我的同城促销订单")
    public String getMyHuigouOrder(
            @ApiParam(value = "用户id") @RequestParam(value = "userid") String userid,
            @ApiParam(value = "页码") @RequestParam(value = "page") int page
    ){
            Map<String,Object> resMap = orderService.getMyHuigouOrder(userid,page);
        return JsonUtil.jsonMapStr(resMap);
    }

    @ResponseBody
    @PostMapping(value = "/cancelHuigouOrder",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "取消惠购订单")
    public String cancelHuigouOrder(
            @ApiParam(value = "订单id") @RequestParam(value = "orderid") String orderid
    ){
        Map<String,Object> resMap = orderService.cancelHuigouOrder(orderid);
        return JsonUtil.jsonMapStr(resMap);
    }


    @ResponseBody
    @PostMapping(value = "/huigouPinglun",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "大商惠购订单评论")
    public String huigouPinglun(
            @ApiParam(value = "订单id") @RequestParam(value = "orderid") String orderid,
            @ApiParam(value = "评论内容") @RequestParam(value = "content") String content
    ){
        Map<String,Object> resMap = new HashMap<>();
        int flag = orderService.huigouPinglun(orderid,content);
        if(flag>0){
            resMap.put("success",true);
            resMap.put("msg","评论成功");
        }else{
            resMap.put("success",false);
            resMap.put("msg","评论失败");
        }
        return JsonUtil.jsonMapStr(resMap);
    }

    @ResponseBody
    @PostMapping(value = "/huigouTousu",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "大商惠购订单投诉")
    public String huigouTousu(
            @ApiParam(value = "订单id") @RequestParam(value = "orderid") String orderid,
            @ApiParam(value = "评论内容") @RequestParam(value = "content") String content
    ){
        Map<String,Object> resMap = new HashMap<>();
        int flag = orderService.huigouTousu(orderid,content);
        if(flag>0){
            resMap.put("success",true);
            resMap.put("msg","投诉成功");
        }else{
            resMap.put("success",false);
            resMap.put("msg","投诉失败");
        }
        return JsonUtil.jsonMapStr(resMap);
    }

    @ResponseBody
    @PostMapping(value = "/getVipTaocan",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "vip套餐")
    public String getVipTaocan(){
        Map<String,Object> resMap = new HashMap<>();
        List<TAbbTaocan> list = taocanService.getVipTaocan();
        if(list.size()>0){
            resMap.put("list",list);
            resMap.put("success",true);
            resMap.put("msg","获取vip套餐成功");
        }else{
            resMap.put("success",false);
            resMap.put("msg","获取vip套餐失败");
        }
        return JsonUtil.jsonMapStr(resMap);
    }


    @ResponseBody
    @PostMapping(value = "/createVipOrder",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "创建vip订单")
    public String createVipOrder(
            @ApiParam(value = "用户id") @RequestParam(value = "userid") String userid,
            @ApiParam(value = "vip套餐id") @RequestParam(value = "taocanid") String taocanid
    ){
        Map<String,Object> resMap = orderService.createVipOrder(userid,taocanid);
        return JsonUtil.jsonMapStr(resMap);
    }


    @ResponseBody
    @PostMapping(value = "/createWxOrder",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "微信统一下单接口")
    public String createWxOrder(HttpServletRequest request,
            @ApiParam(value = "订单id") @RequestParam(value = "orderid") String orderid
    ){
        String ip = HttpUtil.getRemoteHost(request);
        Map<String,Object> resMap = orderService.createWxOrder(orderid,ip);
        return JsonUtil.jsonMapStr(resMap);
    }

    @PostMapping(value = "/getWxPayResult")
    @Transactional
    public void getWxPayResult(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("UTF-8");
        logger.info("------------------------------------------进入回调---------------------------------------------------");
        PrintWriter out = null;
        String return_data = "";
        try {
            out = response.getWriter();
            InputStream input = request.getInputStream();
            StringBuffer strOut = new StringBuffer();
            byte[] b = new byte[4096];
            for (int n; (n = input.read(b)) != -1;) {
                strOut.append(new String(b, 0, n));
            }
            String result = strOut.toString();
            // 过滤
            result = result.replaceAll("<![CDATA[|]]>", "");
            logger.info("----------------返回参数："+result);
            Map<String, Object> resultMap = XMLUtil.doXMLParse(result);
            if (resultMap != null) {
                if (!resultMap.get("return_code").toString().equals("SUCCESS")) {
                    return_data = XMLUtil.setXML("FAIL", "return_code不正确");
                    logger.info("---------------------------------------------return_code不正确------------------------------------------------");
                } else {
                    String out_trade_no = resultMap.get("out_trade_no").toString();
                    // 支付成功时间
                    System.out.println("交易成功");
                    //获取订单
                    TAbbOrder of = orderService.getOrderFormByOrderNo(out_trade_no);
                    if (of == null) {
                        return_data = XMLUtil.setXML("FAIL", "订单不存在");
                        logger.info("---------------------------------------------订单不存在------------------------------------------------");
                    } else {
                        // 如果订单已经支付返回错误
                        if ("1".equals(of.getPaystatus())) {
                            System.out.println("订单已经支付");
                            return_data = XMLUtil.setXML("SUCCESS", "OK");
                            logger.info("---------------------------------------------订单已支付------------------------------------------------");
                        } else {
                            BigDecimal amount = new BigDecimal(of.getPaymoney());
                            amount = amount.multiply(new BigDecimal("100"));
                            int amount1 = amount.intValue();
                            amount = new BigDecimal(amount1);
                            BigDecimal total_fee = new BigDecimal(resultMap.get("total_fee").toString());
                            // 如果支付金额不等于订单金额返回错误
                            if (amount.compareTo(total_fee) != 0) {
                                System.out.println("资金异常");
                                System.out.println("amount："+amount);
                                System.out.println("total_fee："+total_fee);
                                return_data = XMLUtil.setXML("FAIL", "金额异常");
                                logger.info("---------------------------------------------金额异常------------------------------------------------");
                            } else {
                                orderService.handlePayInfo(of);
                                return_data = XMLUtil.setXML("SUCCESS", "OK");
                                logger.info("---------------------------------------------回调成功------------------------------------------------");
                            }
                        }
                    }
                }
            } else {
                return_data = XMLUtil.setXML("FAIL", "签名错误");
                logger.info("---------------------------------------------签名错误------------------------------------------------");
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return_data = XMLUtil.setXML("FAIL", "签名错误");
            logger.info("---------------------------------------------签名错误------------------------------------------------");
        }
        if (out != null) {
            out.write(return_data);
            out.flush();
            out.close();
        }
    }


    /**
     * 测试回调
     * @throws ParseException
     */
    @ResponseBody
    @PostMapping(value = "/callBackTest",produces = {"application/json; charset=utf-8"})
    @ApiOperation(value = "支付回调测试")
    public void callBackTest(
            @ApiParam(value = "订单id") @RequestParam(value = "orderid") String orderid
    ) throws ParseException {
        TAbbOrder order = orderService.selectByPrimaryKey(orderid);
        orderService.handlePayInfo(order);
    }

}
